﻿using System;
using UnityEngine;
using UnityEngine.UIElements;

//将Label作为子物体而非将自身作为HyperlinkText
//这可以避免在水平方向上错误的延展下划线

namespace winS.UnityEditor.UIElement
{
    /// <summary>
    /// 超链接文本控件
    /// </summary>
    public class HyperlinkText : VisualElement
    {
        public static readonly Color textColor = new Color32(76, 126, 255, 255);

        public event Action onClick;

        public string text { get => label.text; set => label.text = value; }

        private readonly Label label;
        private readonly HorizontalSplitline underline;

        internal HyperlinkText()
        {
            style.alignItems = Align.Center;
            style.flexDirection = FlexDirection.Row;

            Add(label = EditorElementUtility.elementFactory.CreateLabel());
            label.style.SetColor(textColor);
            label.style.SetCursor(global::UnityEditor.MouseCursor.Link);
            label.RegisterCallback<MouseEnterEvent>(MouseEnterCallback);
            label.RegisterCallback<MouseLeaveEvent>(MouseLeaveCallback);
            EditorElementUtility.RegisterClickEvent(label, () => onClick?.Invoke());

            Add(underline = EditorElementUtility.elementFactory.CreateHorizontalSplitline(textColor));
            underline.pickingMode = PickingMode.Ignore;
            underline.style.display = DisplayStyle.None;
            underline.style.position = Position.Absolute;
            underline.style.SetBottom(8f, LengthUnit.Percent);
            underline.style.SetWidth(100f, LengthUnit.Percent);
        }

        private void MouseEnterCallback(MouseEnterEvent mouseEnterEvent)
        {
            if (!enabledSelf) return;
            underline.style.display = DisplayStyle.Flex;
        }
        private void MouseLeaveCallback(MouseLeaveEvent mouseLeaveEvent)
        {
            underline.style.display = DisplayStyle.None;
        }
    }
}